package com.wanxi.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.wanxi.dao.ManagerDao;
import com.wanxi.dto.ResultDTO;
import com.wanxi.model.Manager;
import com.wanxi.service.LoginService;
import com.wanxi.util.JwtUtil;
import com.wanxi.vo.ManagerVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    ManagerDao managerDao;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    AuthenticationManager authenticationManager;

    @Override
    public ResultDTO login(ManagerVO managerVO) {

        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(managerVO.getManagerName(), managerVO.getPassword());

        //获取正确的验证码
        String vCode = stringRedisTemplate.opsForValue().get("vCode");
        //判断验证码是否过期
        if(Objects.isNull(vCode)){
            return errorDTO(-1,"验证码已过期！",managerVO);
        //判断验证码是否正确
        }else if (!vCode.equals(managerVO.getCode())) {
            return errorDTO(-1,"验证码错误",managerVO);
        }
        //使用Token进行登录认证
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断是否通过登录认证
        if (Objects.isNull(authenticate)) {
            return errorDTO(1,"用户名或密码错误",managerVO);
        }else {
            Manager manager = (Manager) authenticate.getPrincipal();
            String jwt = JwtUtil.createJWT(manager.getId(), 30 * 60 * 1000);
            stringRedisTemplate.opsForValue()
                    .set("loginManager:"+manager.getId(), JSONObject.toJSONString(manager),30, TimeUnit.MINUTES);
            return ResultDTO.builder()
                    .data(jwt)
                    .count(1)
                    .code(0)
                    .msg(manager.getManagerName())
                    .build();
        }
    }

    private ResultDTO errorDTO(Integer code, String msg, ManagerVO managerVO) {
        return ResultDTO.builder().code(code).msg(msg).count(0).data(managerVO).build();
    }

}
